var Color = net.brehaut.Color;
const poiVert = function (lng, lat) {
  if ($Config.L_MAP_LngLat_SYS == 'GCJ02') {
    return [lng, lat];
  } else if ($Config.L_MAP_LngLat_SYS == 'Baidu') {
    return coordtransform.gcj02tobd09(lng, lat);
  } else {
    return coordtransform.gcj02towgs84(lng, lat);
  }
};

const poiVertRevert = function (lng, lat) {
  if ($Config.L_MAP_LngLat_SYS == 'GCJ02') {
    return [lng, lat];
  } else if ($Config.L_MAP_LngLat_SYS == 'Baidu') {
    return coordtransform.bd09togcj02(lng, lat);
  } else {
    return coordtransform.wgs84togcj02(lng, lat);
  }
};

class LwMap {
  /**
   * 全局对象：
   * this.map 真实的map对象
   * this.mapBox map中存放覆盖物的容器
   */

  /**xxx
   * 构造方法
   * container: DOM ID
   * center: 中心点 eg: [116.404, 39.915] 北京
   * zoom: 缩放级别 {Number | Array(3)[zoom, minZoom, maxZoom]}
   */
  constructor(container, center = [116.404, 39.915], zoom = [11, 3, 18], extraConfig = {}) {
    var isNy = !location.href.includes('localhost'); // 内网
    var layers = '';
    var isEPSG4326 = !$Config.L_MAP_EPSG || $Config.L_MAP_EPSG.includes('4326');
    if ($Config.layerConfig) {
      layers = $Config.layerConfig.url.map((n, i) => {
        return new maptalks.TileLayer('base' + i, {
          urlTemplate : n,
          subdomains: $Config.layerConfig.subdomains,
          errorTileUrl: '/api/icon/images/nopng.png',
          tileSize: 256,
          minZoom: $Config.ZOOMS[0] || zoom[0],
          maxZoom: $Config.ZOOMS[1] || zoom[1],
          ...(isEPSG4326 ? {tileSystem : [1, -1, -180, 90]} : {})
        });
      });
    }
    if (!layers) {
      if (isNy) {
        layers = [
          'http://t{s}.tianditu.gov.cn/DataServer?T=vec_c&tk=3f4a97ee5cf6315de1ad7fb4ac94cd75&x={x}&y={y}&l={z}',
          'http://t{s}.tianditu.gov.cn/DataServer?T=cva_c&tk=3f4a97ee5cf6315de1ad7fb4ac94cd75&x={x}&y={y}&l={z}'
        ].map((n, i) => {
          return new maptalks.TileLayer('base' + i, {
            urlTemplate : n,
						subdomains: ['0','1','2','3','4','5','6'],
            ...(isEPSG4326 ? {tileSystem : [1, -1, -180, 90]} : {}),
            errorTileUrl: '/api/icon/images/nopng.png',
            tileSize: 256,
            minZoom: 11,
            maxZoom: 20
          });
        });
      } else {
        layers = [
          'http://t{s}.tianditu.gov.cn/DataServer?T=vec_c&tk=3f4a97ee5cf6315de1ad7fb4ac94cd75&x={x}&y={y}&l={z}',
          'http://t{s}.tianditu.gov.cn/DataServer?T=cva_c&tk=3f4a97ee5cf6315de1ad7fb4ac94cd75&x={x}&y={y}&l={z}'
        ].map((n, i) => {
          return new maptalks.TileLayer('base' + i, {
            urlTemplate : n,
            subdomains: ['0','1','2','3','4','5','6'],
            ...(isEPSG4326 ? {tileSystem : [1, -1, -180, 90]} : {}),
            errorTileUrl: '/api/icon/images/nopng.png',
            tileSize: 256,
            maxZoom: 18
          });
        });
      }
    }

    var p84 = poiVert(center[0], center[1]);
    if (extraConfig.rotation) {
      extraConfig.bearing = extraConfig.rotation;
    }
    var map = new maptalks.Map(container, {
      ...(isEPSG4326 ? {
        spatialReference : {
          projection: 'EPSG:4326'
        }
      } : {
        ...($Config.L_MAP_INITCONFIG || [])
      }),
      preferCanvas: true,
      zoom: zoom[0],
      minZoom: isNy ? ($Config.ZOOMS && $Config.ZOOMS[0] || 11) : zoom[1],
      maxZoom: isNy ? ($Config.ZOOMS && $Config.ZOOMS[1] || 20) : zoom[2],
      layers: layers,
      center: [p84[0], p84[1]],
      ...extraConfig
    });
    var vm = this;
    vm.map = map;
    vm.mapBox = {}; // 所有地图元素的数组
    vm.obj3DBoundBox = new maptalks.VectorLayer('ThreeDBox').addTo(map);
    vm.layerBox = new maptalks.VectorLayer('vector').addTo(map);

    vm.loadPromise = new Promise((resolve) => {
      resolve();
    });
  }

  showHeatOverLay(data) {
    if (this.heatmapOverlay) {
      this.map.removeLayer(this.heatmapOverlay);
    }
    if (!data) {
      var center = this.map.getCenter();
      data = new Array(10000).fill(1).map(() => {
        return {
          count: Math.random() * 300, 
          lng: center.x + (0.5 - Math.random()) / 2,
          lat: center.y + (0.5 - Math.random()) / 3 
        };
      });
    }
    data.forEach(n => {
      var p84 = poiVert(n.lng, n.lat);
      n.lng = p84[0];
      n.lat = p84[1];
    });
    data = data.map(n => {
      var p84 = poiVert(n.lng, n.lat);
      return [p84[0], p84[1], n.count];
    });
    var heatmapOverlay = new maptalks.HeatLayer('heat', data, {
      radius: 15,
      minOpacity: 0.5,
      max: _.max(data.map(n => n.count))
    }).addTo(this.map);
    this.heatmapOverlay = heatmapOverlay;
    return heatmapOverlay;
  }
  addOuterPolygon() {

  }

  // 需要实现的方法
  /**
   * 地图移动
   * 参数 二维坐标
   */
  panTo(point) {
    var p84 = poiVert(point[0], point[1]);
    this.map.panTo(new maptalks.Coordinate(p84[0], p84[1]));
  }

  addControlBar(offset = [0, 0], zoom = 1) {}

  /**
   * 设置地图缩放级别
   * 参数 zoom
   */
  setZoom(zoom) {
    this.map.setZoom(zoom);
  }

  getZoom() {
    return this.map.getZoom();
  }

  /**
   * 设置地图缩放级别
   */
  setCenterAndZoom(point, zoom) {
    var p84 = poiVert(point[0], point[1]);
    // this.map.setView({
    //   center: p84,
    //   zoom
    // });
    this.map.animateTo({
      center: p84,
      zoom
    }, {
      duration: 800
    });
  }

  /*
   * 增加标注物
   * 参数 id，url, 坐标点, 图片偏移，点击事件
   */
  addMarker(id, url, point, size, offset, onclick, params, labelName) {
    var p84 = poiVert(point[0], point[1]);
    var marker = new maptalks.Marker(p84, {
      'id': id,
      'symbol' : [{
          'markerFile'  : url,
          'markerWidth' : size[0],
          'markerHeight': size[1],
          markerPathWidth: offset[0],
          markerPathHeight: offset[1]
      }, 
        labelName ? {
          'textFaceName' : 'sans-serif',
          'textName' : labelName,
          'textSize' : 14,
          'textFill' : '#000',
          'textHaloFill' : '#fff',
          'textHaloRadius' : 2
        } : {}
      ],
      'properties' : params
    });

    onclick && marker.on('click', onclick);
    marker = _.extend(marker, params);
    // if (labelName) {
    //   var text = new maptalks.Label(labelName, p84, {
    //     'textSymbol': {
    //       'textFaceName' : 'monospace',
    //       'textFill' : '#000',
    //       'textHaloFill' : '#fff',
    //       'textHaloRadius' : 2,
    //       'textSize' : 14,
    //       textDy: 10,
    //       'textVerticalAlignment' : 'top'
    //     }
    //   });
    //   marker.linkObject = [text];
    // }
    if (id == 'CurrentEvent') {
      this.setAnimation(marker);
    }
    this.__addObject(id, marker);
  }
  addMarkerUI(id, url, point, size, offset, onclick, params, labelName = '') {
    var p84 = poiVert(point[0], point[1]);
    var marker = new maptalks.ui.UIMarker(p84, {
      'id': id,
      content:
        `<div class="custom-content-marker ${id} ${params.markerClass || ''}">
        <img ${size ? `width="${size[0]}" height="${size[1]}"` : ''}  src="${url}">
        ${params.markerExtra || ''}
        <div class="label=marker">${labelName}</div>
      </div>`,
      dx: size[0] / 2 - offset[0],
      dy: size[1] / 2 - offset[1],
      eventsPropagation: false,
      eventsToStop: 'click',
      'properties' : params
    });

    onclick && marker.on('click', onclick);
    marker = _.extend(marker, params);
    this.__addObject(id, marker);
  }
  setAnimation (element, className, time = 2000) {
    element.flash(150, 3);
  }
  removeAnimation() {}

  addBreatheMarker(id, url, point, size, offset, defaultShow, onclick, params, labelName) {
    var p84 = poiVert(point[0], point[1]);
    var marker = new maptalks.Marker(p84, {
      'id': id,
      'symbol' : [{
          'markerFile'  : url,
          'markerWidth' : size[0],
          'markerHeight': size[1],
          markerPathWidth: offset[0],
          markerPathHeight: offset[1]
      }, 
        labelName ? {
          'textFaceName' : 'sans-serif',
          'textName' : labelName,
          'textSize' : 14,
          'textFill' : '#000',
          'textHaloFill' : '#fff',
          'textHaloRadius' : 2
        } : {}
      ],
      eventsPropagation: true,
      eventsToStop: 'click',
      animation: 'fade,scale',
      'properties' : params
    });

    onclick && marker.on('click', onclick);
    marker = _.extend(marker, params);
    if (!defaultShow) {
      marker.hide();
    }
    this.__addObject(id, marker);
  }

  // 移除物体 参数 name : 需要删除物体的ID
  removeObject(name) {
    var obj = this.mapBox[name];
    if (obj) {
      obj.linkObject && obj.linkObject.forEach(lo => {
        this.layerBox.removeGeometry(lo);
      });
      this.layerBox.removeGeometry(obj);
    }
    delete this.mapBox[name];
  }

  add3DBoundaryByFeatureV2(feature, rgb, opacity = 0.7, height = 2000, zooms = '', onclick = '', type = '') {
    var bounds = [];
    feature.geometry.coordinates.forEach(coordinate => {
      var b = [];
      coordinate.forEach(function (i) {
        var p84 = poiVert(i[0], i[1]);
        b.push(p84);
      });
      bounds.push(b);
    });

    var color = this.__getRandomRgbColor();
    color = `rgb(${color[0]},${color[1]},${color[2]})`;
    var constructor = bounds.length > 1 ? maptalks.MultiPolygon : maptalks.Polygon;
    var mesh = new constructor(
    // var mesh = new maptalks.Polygon(
      bounds, {
      symbol: {
        'lineColor': 'cyan',
        'lineWidth': 4,
        'lineDasharray': null,//线形
        'lineOpacity': 1,
        'polygonFill': color,
        'polygonOpacity': opacity
      }
    });
    
    var cp84 = poiVert(feature.properties.cp[0], feature.properties.cp[1]);
    var text = new maptalks.Label(feature.properties.name, cp84, {
      'textSymbol': {
        'textFaceName' : 'monospace',
        'textFill' : '#34495e',
        'textHaloFill' : '#fff',
        'textHaloRadius' : 2,
        'textSize' : 14,
        'textWeight' : 'bold',
        'textVerticalAlignment' : 'top'
      }
    });

    mesh.zooms = zooms;
    mesh.lwType = type || feature.type;
    mesh.linkObject = [text];
    mesh.lwcolor = color;
    if (onclick) {
      mesh.addEventListener("click", (e) => {
        if (this.infoWindow && this.infoWindow.isVisible()) {
          this.infoWindow.hide();
          return;
        }
        let p = coordtransform.wgs84togcj02(e.coordinate.x, e.coordinate.y);
        onclick(feature, p);
      });
    }
    mesh.addEventListener("mouseover", function () {
      mesh.setSymbol({
        'lineColor': 'yellow',
        'lineWidth': 6,
        'polygonOpacity': 0
      });
    });
    mesh.addEventListener("mouseout", function () {
      mesh.setSymbol({
        lineColor: 'cyan',
        lineWidth: 4,
        polygonOpacity: opacity,
        'polygonFill': color
      });
    });
  
    this.__addObject(feature.id + '_mesh', mesh, this.obj3DBoundBox);
  }

  add2DPolygon (boundArray, strokeWeight = 1, strokeColor = '#00eeff', fillColor = '#71B3ff', fillOpacity = 0.5) {
    var bounds = [];
    boundArray.forEach(coordinate => {
      var b = [];
      coordinate.forEach(function (i) {
        b.push(poiVert(i[0], i[1]));
      });
      bounds.push(b);
    });
    var mesh = new maptalks.Polygon(
      bounds, {
      symbol: {
        'lineColor': strokeColor,
        'lineWidth': strokeWeight,
        'lineDasharray': null,//线形
        'lineOpacity': 1,
        'polygonFill': fillColor,
        'polygonOpacity': fillOpacity
      }
    });
    mesh.lwType = '2DPolygon';
    this.__addObject((((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1), mesh);
  }
  /**
   * 清除类型为type的所有网格
   */
  removeFeature(type) {
    var vm = this;
    vm.obj3DBoundBox.forEach(n => {
      if (n.linkObject) {
        n.linkObject.forEach(cn => {
          vm.layerBox.removeGeometry(cn);
        });
      }
      vm.obj3DBoundBox.removeGeometry(n);
    });
  }

  /**
   * 设置轨迹路线
   * 轨迹数组 pathArr: [[a,b], [a,b]],
   * 图片路径 imgPath: url,
   * 图片大小 imgSize: [num,num],
   * 图片锚点 imgAncher: [num,num],
   * 图片标签名称 lableName: 'abc',
   * 图片标签偏移 labelOffset: [num,num],
   * 图片与锚点的位置 position: /BL、BM、BR、ML、MR、TL、TM、TR分别代表左下角、底部中央、右下角、左侧中央、右侧中央、左上角、顶部中央、右上角,
   * 轨迹线 lineColor: '#aaaa',
   * 轨迹线宽 lineWeight : num,
   * 点移动速度 speed : num,
   * return 点操控办法:start, pause, resume, stop, setSpeed, setPassLine
   */
  addMarkerAndPath(pathArr, imgPath, imgSize, imgAncher, lableName = '', labelOffset = [-35, 0], position = 'BM', lineColor = '#1104c7', lineWeight = 10, speed = 1000) {
    var vm = this;
    // 删掉老的
    this.removeMarkerAndPath();
    var marker = this.__buildElasticMarker(pathArr[0][0], imgPath, imgSize, imgAncher, lableName, labelOffset, position);
    !marker.linkObject && (marker.linkObject = []);
    var points = [];
    pathArr.forEach((apath) => {
      apath.forEach(point => {
        var p84 = poiVert(point[0], point[1]);
        points.push([p84[0], p84[1]]);
      });
    });

    var line = new maptalks.LineString(points, {id: 'lineOrigin', symbol: {'lineColor': 'red', 'lineWidth': 1}});
    var lineRun = new maptalks.LineString([], {id: 'linerun', symbol: {'lineColor': 'yellow', 'lineWidth': 1}});

    // var line = L.polyline(points, {color: 'red'}).addTo(this.map);  // 轨迹红线
    // var lineRun = L.polyline([], {color: 'yellow'}).addTo(this.map); // 走完的涂绿色
    marker.linkObject.push(line);
    marker.linkObject.push(lineRun);
    this.__addObject('pathAndMarker', marker);
    return {
      marker: marker,
      map: this.map,
      status: 0, // 0 停止   1: 在跑  2: 暂停,
      speed: speed,
      pathArr: points,
      lineRun,
      afterMoveAlongEnd: function () {
        console.log('跑完第' + ++this.pathIndex + '段');
        var nextPath = this.path[this.pathIndex];
        if (nextPath) {
          this.run(this.speed, this.pathIndex);
        }
      },
      afterMoveTo: function () {
        this.run(this.speed);
      },
      init: function () {
        this.pathArr = vm.__getDelicatePoints(points);
        this.pointIndex = [0, 0];
      },
      run: function (v) {
        if (v) {
          this.speed = 100000 / v;
          this.status = 1;
        }
        var nextPointIndex = this.pointIndex[0] + 1;
        if (this.pathArr[nextPointIndex]) {
          this.pointIndex = [nextPointIndex, 0];
          var nextPoint = this.pathArr[nextPointIndex];
          var pathArrRun = this.pathArr.slice(0, nextPointIndex);
          if (this.status == 1) {
            setTimeout(() => {
              this.marker.setCoordinates(nextPoint);
              this.lineRun.setCoordinates(pathArrRun);
              this.run();
            }, this.speed);
          }
        } else {
          // 结束了
          this.pointIndex = [0, 0];
          this.status = 0;
        }
      },
      setSpeed: function (speed) {
        this.speed = 100000 / speed;
      },
      /**
       * 设置点暂停
       */
      pause: function () {
        if (this.status == 2) {
          return;
        }
        this.status = 2;
      },
      changeStep: function (offset) {
        offset *= 2;
        var status = this.status;
        if (this.status != 0) {
          var pointIndex = this.pointIndex[0] + offset;
          var point = this.pathArr[pointIndex];
          if (!point) {
            pointIndex = offset > 0 ? this.pathArr.length - 1 : 1;
            point = this.pathArr[pointIndex];
          }
          this.pointIndex[0] = pointIndex;
          if (status == 2) {
            this.marker.setLatLng(point);
          }
        }
      },
      /**
       * 设置点继续移动
       */
      resume: function () {
        if (this.status == 1) {
          return;
        }
        if (this.status == 2) {
          this.status = 1;
          this.run();
        }
      },
      /**
       * 设置点停止
       */
      stop: function () {
        if (this.status == 0) {
          return;
        }
        this.status = 0;
        this.pointIndex = [0, 0];
      },
      /**
       * 设置已经行驶的路线
       * 已行驶路线颜色 lineColor
       * 已行驶路线透明度 lineopacity
       * 已行驶路线线宽 lineWeight
       * 已行驶路线直线样式 lineStyle
       */
      setPassLine: function (lineColor = '#AF5', lineopacity = 1, lineWeight = 6, lineStyle = 'solid') {
        var passedPolyline = new T.Polyline({
          map: this.map,
          strokeColor: lineColor,
          strokeOpacity: lineopacity,
          strokeWeight: lineWeight,
          strokeStyle: lineStyle
        });
        this.marker.on('moving', function (e) {
          passedPolyline.setPath(e.passedPath);
        });
      }
    };
  }
  __getDelicatePoints(points, delicate = 0.01) {
    var result = [];
    // x1, x2, x3, x4, x5, x6
    // o
    for (let i = 0; i < points.length - 1; i++) {
      result.push(points[i]);
      let lng0 = points[i][0];
      let lat0 = points[i][1];
      let lng1 = points[i + 1][0];
      let lat1 = points[i + 1][1];
      var distance = (lng0 - lng1) ** 2 + (lat0 - lat1) ** 2;
      var dx = Math.round(distance / 2e-8); // 要切割dx段  o     1    1    o
      if (dx > 1) {
        dx > 100 && (dx = 100);
        var dltlng = (lng1 - lng0) / dx;
        var dltlat = (lat1 - lat0) / dx;
        for (let j = 1; j < dx; j++) {
          result.push([lng0 + j * dltlng, lat0 + j * dltlat]);
        }
      }
    }
    if (points.length > 1) {
      // 把最后一个点补进去
      result.push(points[points.length - 1]);
    }
    return result;
  }

  addMarkerAndPathV2(pathArr, imgPath, imgSize, imgAncher, lableName = '', labelOffset = [-35, 0], position = 'BM', lineColor = '#1104c7', lineWeight = 10, speed = 1000) {
    var vm = this;
    this.removeMarkerAndPath();
    var marker = this.__buildElasticMarker(pathArr[0], imgPath, imgSize, imgAncher, lableName, labelOffset, position);
    !marker.linkObject && (marker.linkObject = []);
    // 删掉老的
    var points = [];
    pathArr.forEach(point => {
      var p84 = poiVert(point[0], point[1]);
      points.push([p84[0], p84[1]]);
    });
    var line = new maptalks.LineString(points, {id: 'lineWrj', symbol: {'lineColor': 'red', 'lineWidth': 2}});
    marker.linkObject.push(line);
    this.__addObject('pathAndMarker', marker);

    return {
      map: vm.map,
      marker,
      speed: speed,
      historyArr: [points[0]],
      pathArr: points,
      pointIndex: 0,
      line,
      afterMove: function (foo) {
        this.afterMoveCallback = foo;
      },
      start: function (speed) {
        if (speed) {
          this.speed = speed;
        }
        if (this.pointIndex == 0) {
          this.pointIndex = 0;
          this.map.centerAndZoom(this.pathArr[0], 18);
        }
        var nextPoint = this.pathArr[this.pointIndex + 1];
        if (nextPoint) {
          this.pointIndex += 1;
          var vm = this;
          setTimeout(() => {
            console.log('跑到' + this.pointIndex);
            vm.marker.setCoordinates(nextPoint);
            vm.historyArr.push(nextPoint);
            vm.line.setCoordinates(vm.historyArr);
            vm.start(); // 跑完继续跑
          }, this.speed);
        } else {
          console.log(this.pointIndex + '再获取');
          this.afterMoveCallback();
        }
      },
      addPath: function (arr) {
        arr.forEach(point => {
          var p84 = poiVert(point[0], point[1]);
          this.pathArr.push(p84);
        });
        this.start();
      }
    };
  }

  addRoutePath(id, pathArr, lineColor = 'red', lineWeight = 4) {
		var points = [];
		pathArr.forEach(point => {
		  var p84 = poiVert(point[0], point[1]);
		  points.push([p84[0], p84[1]]);
		});
		var line = new maptalks.LineString(points, {id, symbol: {'lineColor': lineColor, 'lineWidth': lineWeight}});
		line.lwType = 'activity';
		this.__addObject(id, line);
    return line;
  }
	
	letMarkerMoveAlongPath (markerId, path, speed, foo) {
	  var vm = this;
	  var marker = vm.mapBox[markerId];
		path = path.map(point => {
		  var p84 = poiVert(point[0], point[1]);
		  return [p84[0], p84[1]];
		});
	  var passedPolyline = new maptalks.LineString([], {id: 'linerun', symbol: {'lineColor': 'yellow', 'lineWidth': 1}});

	  passedPolyline.lwType = 'activity';
	  vm.__addObject('pathM' + markerId, passedPolyline);

    var obj = {
      marker: marker,
      lineRun: passedPolyline,
      pointIndex: [0, 0],
      pathArr: vm.__getDelicatePoints(path),
      run: function (v) {
        if (v) {
          this.speed = 10000 / v;
          this.status = 1;
        }
        var nextPointIndex = this.pointIndex[0] + 1;
        if (this.pathArr[nextPointIndex]) {
          this.pointIndex = [nextPointIndex, 0];
          var nextPoint = this.pathArr[nextPointIndex];
          var pathArrRun = this.pathArr.slice(0, nextPointIndex);
          if (this.status == 1) {
            setTimeout(() => {
              this.marker.setCoordinates(nextPoint);
              this.lineRun.setCoordinates(pathArrRun);
              this.run();
            }, this.speed);
          }
        } else {
          // 结束了
          this.pointIndex = [0, 0];
          this.status = 0;
          foo && foo();
          
        }
      }
    };
    obj.run(speed)
	}
	
  // 移除
  removeMarkerAndPath() {
    var oldMarker = this.mapBox.pathAndMarker;
    if (oldMarker) {
      var linkObjs = oldMarker.linkObject;
      oldMarker.status = 0;
      if (linkObjs) {
        linkObjs.forEach((n) => {
          this.layerBox.removeGeometry(n);
        });
      }
      this.layerBox.removeGeometry(oldMarker);
    }
  }

  getRandomPoint(pathArr) {
    var lngArr = pathArr.map((n) => n[0]);
    var latArr = pathArr.map((n) => n[1]);
    var maxX = _.max(lngArr);
    var minX = _.min(lngArr);
    var maxY = _.max(latArr);
    var minY = _.min(latArr);
    let result = [];
    while (result.length != 50) {
      let lng = minX + (maxX - minX) * Math.random();
      let lat = minY + (maxY - minY) * Math.random();
      result.push([lng, lat]);
    }
    return result;
  }

  /**
   * 清除类型为type的所有网格
   * 删除的3D物体
   */
  removeObjByTypename(type) {
    var vm = this;
    vm.obj3DBoundBox.clear();
  }

  /**
   * 清除地图图标
   */
  clearActivities(foo) {
    var vm = this;
    !foo && (foo = (n) => n.lwType == 'activity' || (n.lwType && n.lwType.includes('Marker')));
    if (foo instanceof Function) {
      var keys = Object.keys(vm.mapBox);
      keys.forEach((key) => {
        let obj = vm.mapBox[key];
        if (foo(obj)) {
          vm.removeObject(key);
        }
      });
    }
  }

  showInfoWindow(content, position, anchor = 'bottom-center') {
    if (this.infoWindow) {
      this.infoWindow.remove();
    }
    if (!content) return;
    var p84 = poiVert(position[0], position[1]);
    var options = {
      // 'custom': true,
      autoCloseOn: 'click',
      autoOpenOn: null,
      eventsPropagation: true,
      'single' : true,
      'dx' : 0,
      'dy' : 0,
      'content': content,
      animationDuration: 100
    };
    var infoWin = new maptalks.ui.InfoWindow(options);
    infoWin.addTo(this.map);
    this.infoWindow = infoWin;
    setTimeout(() => {
      infoWin.show(new maptalks.Coordinate(p84[0], p84[1]));
    }, 200);
  }

  closeInfoWindow() {
    this.infoWindow && this.infoWindow.remove();
  }

  setRotationAndPitch(rotation, pitch) {
    this.map.setView({
      pitch: pitch,
      bearing: rotation
    });
  }

  getRotationAndPitch() {
    var view = this.map.getView();
    return {
      pitch: view.pitch,
      rotation: view.bearing
    };
  }

  addOuterFeature (bounds) {
    if (!(bounds instanceof Array)) {
      bounds = [bounds];
    }
    var masks = [];
    // debugger
    bounds.forEach(bound => {
      var arr = [];
      bound.geometry.coordinates.forEach(coordinate => {
        var b = [];
        coordinate.forEach(function (i) {
          var p84 = poiVert(i[0], i[1]);
          b.push(p84);
        });
        arr.push(b);
      });
      masks.push(arr);
    });

    var constructor = masks.length > 1 ? maptalks.MultiPolygon : maptalks.Polygon;
    // debuggers
    this.map.getLayers().forEach(n => {
      let mesh = new constructor(masks);
      n._id.startsWith('base') && n.setMask(
        mesh
      );
    })
  }

  // 私有方法
  __addObject(id, nobj, layer) {
    var box = layer || this.layerBox;
    var obj = this.mapBox[id];
    if (obj) {
      // 已经有了
      var linkObjs = obj.linkObject;
      if (linkObjs) {
        linkObjs.forEach((n) => {
          this.layerBox.removeGeometry(n);
        });
      }
      box.removeGeometry(obj);
      delete this.mapBox[id];
    }
    nobj.addTo(box);
    if (nobj.linkObject) {
      nobj.linkObject.forEach((n) => {
        n.addTo(this.layerBox);
      });
    }
    this.mapBox[id] = nobj;
  }
  __getRandomRgbColor() {
    return new Array(3).fill(255).map((o) => {
      return parseInt(o * Math.random());
    });
  }


  __buildElasticMarker(position, imgPath, imgSize, imgAncher, labelName = '', labelOffset = [-35, 0], labelPosition = 'BM') {
    var p84 = poiVert(position[0], position[1]);
    var marker = new maptalks.Marker(p84, { 
      'symbol' : [{
          'markerFile'  : imgPath,
          'markerWidth' : imgSize[0],
          'markerHeight': imgSize[1],
          markerPathWidth: imgAncher[0],
          markerPathHeight: imgAncher[1]
      }, 
        labelName ? {
          'textFaceName' : 'sans-serif',
          'textName' : labelName,
          'textSize' : 14,
          'textFill' : '#000',
          'textHaloFill' : '#fff',
          'textHaloRadius' : 2
        } : {}
      ]
    });
    return marker;
  }
}
window.LwMap = LwMap;
